// pages/goods_list/index.js
import {request} from '../../request/index.js'
import regeneratorRuntime from '../../lib/runtime/runtime.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabs: [
      {
        id: 0,
        name: "综合",
        isActive: true
      },
      {
        id: 1,
        name: "销量",
        isActive: false
      },
      {
        id: 2,
        name: "价格",
        isActive: false
      }
    ],
    goodsList: ''
  },
  QueryParams: {
    query: "",
    cid: "",
    pagenum: 1,
    pagesize: 10
  },
  totalPages: 1,
  onLoad: function (options) {
    console.log(options)
    this.QueryParams.cid = options.cid
    this.getGoodsList()
  },
  async getGoodsList() {
    let data = await request({url: "/goods/search",data: this.QueryParams})
    // 获取总条数
    let total = data.data.message.total
    this.totalPages = Math.ceil(total / this.QueryParams.pagesize)
    this.setData({
      goodsList: [...this.data.goodsList , ...data.data.message.goods]
    })
  },
  tabsItemChange: function (e) {
    let index = e.detail.index
    let tabs = this.data.tabs
    tabs.forEach(item => {
      if(item.id === index) {
        item.isActive = true
      } else {
        item.isActive = false
      }
    })
    this.setData({
      tabs
    })
  },
  // 页面上拉触底事件
  onReachBottom: function () {
    // 判断还有没有数据
    if(this.QueryParams.pagenum >= this.totalPages) {
      // 没有下一页数据，提示用户
      wx.showToast({title: '没有下一页数据了'})
    } else {
      this.QueryParams.pagenum++
      this.getGoodsList()
    }
  },
  onPullDownRefresh: function () {
    this.setData({
      goodsList: []
    })
    this.QueryParams.pagenum = 1
    this.getGoodsList()
    // 关闭下拉刷新
    wx.stopPullDownRefresh()   
  }
})
